package Example;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-12-05  10:49
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class RadioButtonExample extends JFrame {
    private JLabel label;

    public RadioButtonExample() {
        setTitle("RadioButton Example");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        label = new JLabel("Select an option");
        add(label);

        JRadioButton plainButton = new JRadioButton("Plain");
        JRadioButton boldButton = new JRadioButton("Bold");
        JRadioButton italicButton = new JRadioButton("Italic");

        ButtonGroup group = new ButtonGroup();
        group.add(plainButton);
        group.add(boldButton);
        group.add(italicButton);

        add(plainButton);
        add(boldButton);
        add(italicButton);

        // 添加事件监听器
        plainButton.addActionListener(new RadioButtonListener("Plain selected"));
        boldButton.addActionListener(new RadioButtonListener("Bold selected"));
        italicButton.addActionListener(new RadioButtonListener("Italic selected"));
    }

    // 自定义的事件监听器类
    private class RadioButtonListener implements ActionListener {
        private String message;

        public RadioButtonListener(String message) {
            this.message = message;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setText(message);
        }
    }

    public static void main(String[] args) {
        // 使用SwingUtilities.invokeLater确保在事件分发线程中执行
        SwingUtilities.invokeLater(() -> {
            RadioButtonExample example = new RadioButtonExample();
            example.setVisible(true);
        });
    }
}

